import json
import uuid
from flask import Blueprint, request
from requests import post, get, RequestException

from procedureLog import ExecutionLog
from service import MasterService

import sql

master = Blueprint('MasterController', __name__)

controllerIp = 'http://127.0.0.1:4000/master/'


# 开启设备功能
@master.route('/openEquipmentFunction', methods=['GET', 'POST'])
def openEquipmentFunction():
    req = json.dumps(request.args)
    return req


# 关闭设备功能
@master.route('/closeEquipmentFunction', methods=['GET', 'POST'])
def closeEquipmentFunction():
    req = json.dumps(request.args)
    return req


# # 下行设备方法
# @master.route('/downEquipmentFunction', methods=['GET', 'POST'])
# def downEquipmentFunction():
#     req = json.dumps(request.args)
#     return req

# 设备上行方法(通过关联关系进行互动)
@master.route('/equipmentUpstream', methods=['GET', 'POST'])
def downEquipmentFunction():
    # return 'hello'
    req = json.loads(request.data)
    sender = req['sender']
    # print(req)
    # print('sender:%s' % sender)
    sender_id = sql.get_device_id(sender)

    # print('id:%s' % sender_id)
    # 写入日志
    taskId = str(uuid.uuid1()) if 'taskId' not in req or not req['taskId'] else req['taskId']
    ExecutionLog.executionLog(taskId=taskId, senderId=sender_id, senderName=sender,
                              interface=controllerIp + 'equipmentUpstream')
    req['taskId'] = taskId
    #
    conn_list = sql.get_connection_device(sender_id)
    # print(conn_list)
    # address_list = []
    req_list = []
    for i in conn_list:
        addr = sql.get_addr(i)
        addr = addr + '/downEquipmentFunction'
        article_info = {}
        status_code = 400
        try:
            r = post(url=addr, data=req)
            status_code = r.status_code
            if status_code == 200:
                article_info = {'addresseeId': i, 'status_code': status_code, 'message': r.json()}
            else:
                article_info = {'addresseeId': i, 'status_code': status_code}
        except Exception:
            article_info = {'addresseeId': i, 'status_code': status_code}
        article = json.dumps(article_info)
        req_list.append(article)
        addresseeName = sql.get_device(i)[1]
        # 写入日志
        ExecutionLog.executionLog(taskId=taskId, addresseeId=i, addresseeName=addresseeName,
                                  interface=addr, statusCode=status_code)
    return req_list


# 服务实时视频画面
@master.route('/liveVideo', methods=['GET', 'POST'])
def givenEquipmentUpstream():
    req = json.loads(request.data)
    addresseeId = req["addresseeId"]  # 收件人id
    sender = req["sender"]
    # 通过数据库查询，获取收件人地址
    addr = sql.get_addr(addresseeId)

    # 写入日志
    taskId = str(uuid.uuid1()) if 'taskId' not in req or not req['taskId'] else req['taskId']
    ExecutionLog.executionLog(taskId=taskId, senderName=sender,
                              interface=controllerIp + 'liveVideo')
    #
    addrJosn = {'addr': addr, "taskId": taskId}
    print('get live video')
    return json.dumps(addrJosn, sort_keys=True, indent=4, separators=(',', ': '))


# 单独指定设备上行方法
@master.route('/appointEquipmentUpstream', methods=['GET', 'POST'])
def appointEquipmentUpstream():
    req = json.loads(request.data)
    sender = req["sender"]
    addresseeId = req["addresseeId"]  # 收件人id
    describe = req['command']['target']
    print(describe)
    device = sql.get_device(addresseeId)
    addr = str(device[3])
    addresseeName = device[1]
    # 写入日志
    taskId = str(uuid.uuid1()) if 'taskId' not in req or not req['taskId'] else req['taskId']
    ExecutionLog.executionLog(taskId=taskId, senderName=sender, describe=describe,
                              interface=controllerIp + 'appointEquipmentUpstream')
    #
    req['taskId'] = taskId
    addr = addr + '/downEquipmentFunction'
    req = json.dumps(req)
    status_code = 400
    try:
        req_info = post(url=addr, data=req)
        status_code = req_info.status_code
        req_info = req_info.json()
    except Exception:
        req_info = {'error': '子设备连接错误'}
    # 写入日志
    ExecutionLog.executionLog(taskId=taskId, addresseeId=addresseeId, addresseeName=addresseeName, describe=describe,
                              interface=addr, statusCode=status_code)
    #
    return req_info


# 脑图
@master.route('/relationalBrainMap', methods=['GET', 'POST'])
def relationalBrainMap():
    data = {"data": MasterService.get_relational_brainMap()}
    return data
